package com.example.springbootdemo.web;

import com.example.springbootdemo.app.BizValidateService;
import com.example.springbootdemo.validate.AddGroup;
import com.example.springbootdemo.user.Ret;
import com.example.springbootdemo.validate.UpdateGroup;
import com.example.springbootdemo.user.UserCmd;
import com.example.springbootdemo.validate.ValidPhone;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {
    @Resource
    private BizValidateService bizValidateService;

    @PostMapping("/user/add")
    public ResponseEntity<Ret> createUser(@RequestBody @Validated(AddGroup.class) UserCmd user) {
        // 这里可以添加保存用户到数据库的逻辑
        return ResponseEntity.ok(Ret.suc("User created successfully"));
    }

    @PostMapping("/user/update")
    public ResponseEntity<Ret> update(@RequestBody @Validated(UpdateGroup.class) UserCmd user) {
        // 这里可以添加保存用户到数据库的逻辑
        return ResponseEntity.ok(Ret.suc("User updated successfully"));
    }

    @PostMapping("/user/check")
    public ResponseEntity<Ret> check(@RequestBody UserCmd user) {
        bizValidateService.bizMethodA(user, "check");
        return ResponseEntity.ok(Ret.suc("User updated successfully"));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Ret> handleValidationExceptions(MethodArgumentNotValidException ex) {
        // 获取所有验证错误
        List<FieldError> errors = ex.getBindingResult().getFieldErrors();
        if (!errors.isEmpty()) {

            // 假设这里只是简单地返回第一个错误信息
            FieldError errorMessage = errors.stream().findFirst().orElse(null);
            if (errorMessage != null) {
                return ResponseEntity.badRequest().body(Ret.fail(errorMessage.getDefaultMessage()));
            }
        }
        List<ObjectError> list = ex.getBindingResult().getAllErrors();
        if (!list.isEmpty()) {
            ObjectError error = list.stream().findFirst().orElse(null);
            if (error != null) {
                return ResponseEntity.badRequest().body(Ret.fail(error.getDefaultMessage()));
            }
        }
        return ResponseEntity.badRequest().body(Ret.fail("Invalid request data"));

    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Ret> handleValidationExceptions(Exception ex) {
        return ResponseEntity.badRequest().body(Ret.fail(ex.getMessage()));
    }
}